package org.puremvc.as3.multicore.core
{
	import org.puremvc.as3.multicore.interfaces.IMessage;
	import org.puremvc.as3.multicore.interfaces.IMessageCommand;

	public class Messaging 
	{
		protected var multitonKey:String;
		
		protected var callback:MessagingConnector;
		
		protected var commandMap:Array;
		
		public function Messaging(key:String)
		{
			multitonKey = key;
			commandMap = new Array();
		}
		
		public function get key():String {
			return multitonKey;
		}

		public function send(message:IMessage):void
		{
			callback.send(message);
		}
		
		public function receive(message:IMessage):void
		{
			if( commandMap[ message.getName() ] != null ) {
				
				// Get a reference to the observers list for this notification name
				var commands_ref:Array = commandMap[ message.getName() ] as Array;

				// Copy observers from reference array to working array, 
				// since the reference array may change during the notification loop
   				var commands:Array = new Array(); 
   				var command:IMessageCommand;
				for (var i:Number = 0; i < commands_ref.length; i++) { 
					command = new commands_ref[ i ]() as IMessageCommand;
					command.initializeNotifier( multitonKey );
					commands.push( command );
				}
				
				// Notify Observers from the working array				
				for (i = 0; i < commands.length; i++) {
					command = commands[ i ] as IMessageCommand;
					command.process( message );
				}
			}
		}
		
		public function connector(callback:MessagingConnector):void {
			this.callback = callback;
		}
		
		public function registerMessageCommand(messageName:String, commandClassRef:Class):void {
			if ( commandMap[ messageName ] == null ) {
				commandMap[ messageName ] = new Array();
			}
			commandMap[ messageName ].push(commandClassRef);
		}
		
	}
}